<template>
  <div class="index-wrraper">
    <div class="im-wrapper">
      <oper @close_socket="closeSocket"></oper>
      <friend :friendList="friendList" @chat="chat" :msgCountObj="msgCountObj" @clearMsgCount="clearMsgCount"></friend>
      <chat :friend="curFriend" :socketconn="socket" @msgcount="handlerMsgCount" @clearMsgCount="clearMsgCount"></chat>
    </div>
  </div>
</template>

<script>
import Oper from './Oper.vue';
import Friend from './Friend.vue';
import Chat from './Chat.vue';
import { createUserSocket } from '../utils/socket'

export default {
  name: 'Index',
  components: {
    Oper,
    Friend,
    Chat
  },
  data() {
    return {
      friendList: [],
      curFriend: null,
      username: '',
      id: '',
      socket: null,
      msgCountObj: {}
    }
  },
  mounted() {
    const { username, id } = JSON.parse(this.$storage.getItem('userinfo'));
    this.username = username;
    this.id = id;
    this.getFriends();
    this.initSocket()
    const index = parseInt(this.$storage.getItem('index'));
    if (!index) {
      this.$storage.setItem('index', 1);
    } else {
      this.$storage.setItem('index', index + 1);
    }

  },
  methods: {
    handlerMsgCount(msgCountObj) {
      this.msgCountObj = msgCountObj;
    },
    clearMsgCount(id) {
      this.msgCountObj[id] = 0;
    },
    closeSocket() {
      console.log('closeSocket');
      this.socket && this.socket.disconnect(true);
      this.socket = null;
    },
    initSocket() {
      this.socket = createUserSocket({ id: this.id });
      // 触发 服务端发送userlist事件
      this.socket.emit('chat', JSON.stringify({ msg: '链接成功', from: this.id, time: '' }))
      this.socket.on('userlist', (data) => {
        this.friendList = JSON.parse(data).data;
      })
      // 服务端先发送给客户端  客户端接收到后再发送给服务端 必须发送1
      this.socket.on('online', () => {
        this.socket.emit('online', 1);
      })
    },
    chat(friend) {
      this.curFriend = friend;
    },
    getFriends() {
      // 获取好友列表
      this.$axios.get(`/users/getFriends?username=${this.username}&id=${this.id}`).then(res => {
        this.friendList = []
        if (res.data.code === 200) {
          this.friendList = res.data.data;
        }
      })
    }
  }
}
</script>

<style scoped>
.index-wrraper {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  background-color: rgb(235, 174, 174);
}

.im-wrapper {
  width: 100%;
  height: 100%;
  background-color: black;
  overflow: hidden;
  display: flex;
}
</style>